<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <!-- 引入样式 -->
    <link rel="stylesheet" href="../../plugins/element-ui/index.css"/>
    <link rel="stylesheet" href="../../styles/common.css"/>
    <link rel="stylesheet" href="../../styles/page.css"/>
    <link rel="stylesheet" href="../../element-ui/lib/theme-chalk/index.css">
</head>
<body>
<div class="dashboard-container" id="purchaseDetail-app">
    <div class="container">
        <div class="tableBar">
            <el-button
                    type="primary"
                    class="continue"
                    @click="addClass('class')">
                + 新增进货药品
            </el-button>
            <el-button
                    type="primary"
                    @click="addPurchase()">
                + 生成进货单
            </el-button>
        </div>
        <el-table
                :data="tableData"
                stripe
                class="tableBox">

            <el-table-column
                    prop="name"
                    label="药品名称"/>
            </el-table-column>


            <el-table-column
                    prop="purchasePrice"
                    label="进货单价(元)"/>
            </el-table-column>

            <el-table-column
                    prop="purchaseCount"
                    label="进货数量"/>
            </el-table-column>

            <el-table-column
                    prop="totalPrice"
                    label="进货总价(元)"/>
            </el-table-column>

            <el-table-column
                    prop="produceDate"
                    label="生产日期">
                <template slot-scope="scope">
                    {{scope.row.produceDate}}
                </template>
            </el-table-column>

            <el-table-column
                    prop="effectiveDate"
                    label="有效日期">
                <template slot-scope="scope">
                    {{scope.row.effectiveDate}}
                </template>
            </el-table-column>


            <el-table-column
                    label="操作"
                    width="200"
                    align="center">
                <template slot-scope="scope">
                    <el-button
                            type="text"
                            size="small"
                            class="blueBug"
                            @click="editHandle(scope.row)">
                        修改
                    </el-button>
                    <el-button
                            type="text"
                            size="small"
                            class="delBut non"
                            @click="deleteHandle(scope.row.id)">
                        删除
                    </el-button>
                    <el-button
                            type="text"
                            class="blueBug"
                            size="small"
                            @click="showDrugHandle(scope.row)">
                        药品详情
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
                class="pageList"
                :page-sizes="[10, 20, 30, 40]"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="counts"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
        ></el-pagination>
    </div>

    <el-dialog title="药品信息" :visible.sync="dialogTableVisible">
        <el-form ref="gridData" :model="gridData" label-width="80px">
            <el-form-item label="药品名称:">
                <el-input v-model="gridData.name" disabled="disabled"></el-input>
            </el-form-item>
            <el-form-item label="药品编号:">
                <el-input v-model="gridData.drugId" disabled="disabled"></el-input>
            </el-form-item>

            <el-form-item label="药品编号:">
                <el-image style="width: auto; height: auto; border:none;cursor: pointer;"
                          :src="getImage(gridData.image)"
                          :preview-src-list="[ `/common/download?name=${gridData.image}` ]">
                    <div slot="error" class="image-slot">
                        <img src="./../../images/404-images/404-cloud.png"
                             style="width: auto; height: 40px; border:none;">
                    </div>
                </el-image>
            </el-form-item>

            <el-form-item label="计量单位:">
                <el-input v-model="gridData.unit" disabled="disabled"></el-input>
            </el-form-item>
            <el-form-item label="药品类型:">
                <el-input v-model="gridData.type" disabled="disabled"></el-input>
            </el-form-item>
            <el-form-item label="药品功效:">
                <el-input type="textarea" v-model="gridData.efficacy" disabled="disabled"></el-input>
            </el-form-item>
        </el-form>
    </el-dialog>

    <el-dialog
            :title="classData.title"
            :visible.sync="classData.dialogVisible"
            width="30%"
            :before-close="handleClose">
        <el-form
                class="demo-form-inline"
                label-width="100px">

            <el-form-item
                    label="药品:"
                    prop="drugId">
                <el-select
                        v-model="classData.drugId"
                        placeholder="请选择药品">
                    <el-option v-for="(item,index) in drugList" :key="index" :label="item.name" :value="item.id"/>
                </el-select>
            </el-form-item>

            <el-form-item
                    label="进货单价(元):"
                    prop="purchasePrice">
                <el-input
                        v-model="classData.purchasePrice"
                        placeholder="请输入药品进货单价"
                        maxlength="20"/>
            </el-form-item>

            <el-form-item
                    label="进货数量:"
                    prop="purchaseCount">
                <el-input
                        v-model="classData.purchaseCount"
                        placeholder="请输入药品进货数量"
                        maxlength="20"/>
            </el-form-item>

            <el-form-item>
                <template>
                    <div class="block">
                        <span class="demonstration">生产日期:</span>
                        <el-date-picker
                                v-model="classData.produceDate"
                                type="date"
                                value-format="yyyy-MM-dd"
                                placeholder="选择日期">
                        </el-date-picker>
                    </div>
                </template>
            </el-form-item>

            <el-form-item>
                <div class="block">
                    <span class="demonstration">有效日期:</span>
                    <el-date-picker
                            v-model="classData.effectiveDate"
                            type="date"
                            value-format="yyyy-MM-dd"
                            placeholder="选择日期">
                    </el-date-picker>
                </div>
            </el-form-item>

        </el-form>
        <span
                slot="footer"
                class="dialog-footer">
        <el-button
                size="medium"
                @click="classData.dialogVisible = false"
        >取 消</el-button>
        <el-button
                type="primary"
                size="medium"
                @click="submitForm()"
        >确 定</el-button>
        <el-button
                v-if="action != 'edit'"
                type="primary"
                size="medium"
                class="continue"
                @click="submitForm('go')"
        > 保存并继续添加 </el-button>
      </span>
    </el-dialog>

    <el-dialog title="生成进货单" :visible.sync="dialogFormVisible">
        <el-form :model="form">
            <el-form-item label="产商编号:" :label-width="formLabelWidth">
                <el-input v-model="form.id" disabled="disabled" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="产商:" prop="drugId" :label-width="formLabelWidth">
                <el-select v-model="form.id" placeholder="请选择产商">
                    <el-option v-for="(item,index) in manufacturerList" :key="index" :label="item.name"
                               :value="item.id"/>
                </el-select>
            </el-form-item>
            <el-form-item
                    label="备注:"
                    prop="remark"
                    :label-width="formLabelWidth">
                <el-input
                        v-model="form.remark"
                        type="textarea"
                        :rows="3"
                        autocomplete="off"
                        placeholder="进货单备注，最长200字"
                        maxlength="200"
                />
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="addPurchaseHandle()">确 定</el-button>
        </div>
    </el-dialog>
</div>
<!-- 开发环境版本，包含了有帮助的命令行警告 -->
<script src="../../plugins/vue/vue.js"></script>
<!-- 引入组件库 -->
<script src="../../plugins/element-ui/index.js"></script>
<script src="../../element-ui/lib/index.js"></script>
<!-- 引入axios -->
<script src="../../plugins/axios/axios.min.js"></script>
<script src="../../js/request.js"></script>
<script src="../../api/drug.js"></script>
<script src="../../api/purchaseDetail.js"></script>
<script src="../../api/purchase.js"></script>
<script src="../../api/manufacturer.js"></script>
<script src="../../api/category.js"></script>
<script>
    new Vue({
        el: '#purchaseDetail-app',
        data() {
            return {
                action: '',
                counts: 0,
                page: 1,
                pageSize: 10,
                tableData: [],
                type: '',
                drugList: [],
                manufacturerList: [],
                gridData: [],
                dialogTableVisible: false,
                dialogFormVisible: false,
                typeList:[],
                classData: {
                    'title': '添加进货药品',
                    'dialogVisible': false,
                    'id': '',
                    'drugId': '',
                    'purchasePrice': '',
                    'purchaseCount': '',
                    'produceDate': '',
                    'effectiveDate': ''
                },
                form: {
                    id: '',
                    remark: '',
                },
                formLabelWidth: '120px'
            }
        },
        computed: {},
        created() {
            this.init()
        },
        mounted() {
        },
        methods: {
            async init() {
                this.getTypeList()
                await getPurchaseDetailPage({'page': this.page, 'pageSize': this.pageSize}).then(res => {
                    if (String(res.code) === '1') {
                        this.tableData = res.data.records
                        this.counts = Number(res.data.total)
                    } else {
                        this.$message.error(res.msg || '操作失败')
                    }
                }).catch(err => {
                    this.$message.error('请求出错了：' + err)
                })
            },
            handleQuery() {
                this.page = 1;
                this.init();
            },
            // 添加
            addClass(st) {
                this.action = 'add'
                this.classData.drugId = ''
                this.classData.purchaseCount = ''
                this.classData.purchasePrice = ''
                this.classData.produceDate = ''
                this.classData.effectiveDate = ''
                this.getDrugList()
                this.classData.dialogVisible = true
            },
            editHandle(dat) {
                this.classData.title = '修改进货药品'
                this.action = 'edit'
                this.getDrugList()
                this.classData.id = dat.id
                this.classData.drugId = dat.drugId
                this.classData.purchaseCount = dat.purchaseCount
                this.classData.purchasePrice = dat.purchasePrice
                this.classData.effectiveDate = dat.effectiveDate
                this.classData.produceDate = dat.produceDate
                this.classData.dialogVisible = true
            },
            showDrugHandle(data) {
                this.dialogTableVisible = true
                this.gridData = data
                data.unit = data.unit == '0' ? '瓶' : data.unit == '1' ? '支' : '袋'
                for (let type of this.typeList) {
                    if (data.type==type.id) {
                        data.type=type.name
                        break
                    }
                }
            },
            // 关闭弹窗
            handleClose(st) {
                this.classData.dialogVisible = false
            },
            //删除
            deleteHandle(id) {
                this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
                    'confirmButtonText': '确定',
                    'cancelButtonText': '取消',
                    'type': 'warning'
                }).then(() => {
                    deletePurchaseDetail(id).then(res => {
                        if (res.code === 1) {
                            this.$message.success('删除成功！')
                            this.handleQuery()
                        } else {
                            this.$message.error(res.msg || '操作失败')
                        }
                    }).catch(err => {
                        this.$message.error('请求出错了：' + err)
                    })
                })
            },
            // 获取药品列表
            getDrugList() {
                getDrug().then(res => {
                    if (res.code === 1) {
                        this.drugList = res.data
                    } else {
                        this.$message.error(res.msg || '操作失败')
                    }
                })
            },

            // 获取产商列表
            getManufacturer() {
                getManufacturerList().then(res => {
                    if (res.code === 1) {
                        this.manufacturerList = res.data
                    } else {
                        this.$message.error(res.msg || '操作失败')
                    }
                })
            },

            //数据提交
            submitForm(st) {
                const classData = this.classData
                const valid =
                    (classData.drugId === 0 || classData.drugId) &&
                    (classData.purchaseCount === 0 || classData.purchaseCount) &&
                    (classData.purchasePrice === 0 || classData.purchasePrice) &&
                    (classData.produceDate === 0 || classData.produceDate) &&
                    (classData.effectiveDate === 0 || classData.effectiveDate)
                const priceReg = /^(([1-9]\d{0,5})|0)(\.\d{1,2})?$/
                const CountReg = /^[1-9]{1,5}|0\d/
                const dateReg = /^(?:(?!0000)[0-9]{4}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-8])|(?:0[13-9]|1[0-2])-(?:29|30)|(?:0[13578]|1[02])-31)|(?:[0-9]{2}(?:0[48]|[2468][048]|[13579][26])|(?:0[48]|[2468][048]|[13579][26])00)-02-29)$/
                if (!priceReg.test(classData.purchasePrice)) {
                    this.$message.error('药品价格格式错误（整数位不能超过5位，小数位不能超过2位）')
                    return
                }
                if (!CountReg.test(classData.purchaseCount)) {
                    this.$message.error('药品数量格式错误（整数位不能超过5位）')
                    return
                }
                if (!dateReg.test(classData.produceDate) || !dateReg.test(classData.effectiveDate)) {
                    this.$message.error('日期格式错误')
                    return
                }
                if (classData.produceDate > classData.effectiveDate) {
                    this.$message.error('生产日期不能大于有日期')
                    return
                }
                if (this.action === 'add') {
                    if (valid) {
                        addPurchaseDetail({
                            'drugId': classData.drugId,
                            'purchasePrice': classData.purchasePrice,
                            purchaseCount: classData.purchaseCount,
                            produceDate: classData.produceDate,
                            effectiveDate: classData.effectiveDate
                        }).then(res => {
                            console.log(res)
                            if (res.code === 1) {
                                this.$message.success('进货单项添加成功！')
                                if (!st) {
                                    this.classData.dialogVisible = false
                                } else {
                                    this.classData.drugId = ''
                                    this.classData.purchasePrice = ''
                                    this.classData.purchaseCount = ''
                                    this.classData.produceDate = ''
                                    this.classData.effectiveDate = ''
                                }
                                this.handleQuery()
                            } else {
                                this.$message.error(res.msg || '操作失败')
                            }
                        }).catch(err => {
                            this.$message.error('请求出错了：' + err)
                        })
                    }
                } else if (valid) {
                    editPurchaseDetail({
                        id: classData.id,
                        'drugId': classData.drugId,
                        purchasePrice: classData.purchasePrice,
                        purchaseCount: classData.purchaseCount,
                        produceDate: classData.produceDate,
                        effectiveDate: classData.effectiveDate
                    }).then(res => {
                        if (res.code === 1) {
                            this.$message.success('进货表单修改成功！')
                            this.classData.dialogVisible = false
                            this.handleQuery()
                        } else {
                            this.$message.error(res.msg || '操作失败')
                        }
                    }).catch(err => {
                        this.$message.error('请求出错了：' + err)
                    })
                }
            },
            // 打开生成进货单的视图
            addPurchase() {
                this.dialogFormVisible = true
                this.getManufacturer()
            },

            addPurchaseHandle() {
                if (this.form.id==''||this.form.id==null) {
                    this.$message.error('产商不能为空！')
                    return
                }
                if (this.tableData==''||this.tableData==[]) {
                    this.$message.error('进货药品不能为空！')
                    return
                }
                this.$confirm('此操作将生成进货表单, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    addPurchase(this.form).then(res => {
                        if (res.code === 1) {
                            this.$message.success('进货表单生成成功！')
                            this.dialogFormVisible = false
                            this.handleQuery()
                        } else {
                            this.$message.error(res.msg || '操作失败')
                        }
                    }).catch(err => {
                        this.$message.error('请求出错了：' + err)
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            handleSizeChange(val) {
                this.pageSize = val
                this.init()
            },
            handleCurrentChange(val) {
                this.page = val
                this.init()
            },
            getImage(image) {
                return `/common/download?name=${image}`
            },
            getTypeList() {
                queryCategoryList().then(res => {
                    if (res.code === 1) {
                        this.typeList = res.data
                    } else {
                        this.$message.error(res.msg || '操作失败')
                    }
                })
            },
        }
    })
</script>
</body>
</html>